import React, { PureComponent } from 'react'
import CustomTable from 'components/common/table'
import { Modal, Form, Input, message, Select } from 'antd'
import { debounce } from 'utils'

import PropTypes from 'prop-types'

import Style from './relatedCom.css'

const { Option } = Select

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 }
}
const { Search } = Input
class RelatedCom extends PureComponent {
  constructor (props) {
    super(props)
    this.state = {
    }
    this.imageClick = this.imageClick.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleRelated = this.handleRelated.bind(this)
    this.directionChange = this.directionChange.bind(this)
  }

  getTableCols () {
    return [
      {
        title: '标签名',
        dataIndex: 'tagName',
        key: 'tagName',
        width: 100
      },
      {
        title: '坐标',
        dataIndex: 'pos',
        key: 'pos',
        width: 100,
        render: (text, row) => <span>{row.posX},{row.posY}</span>
      },
      {
        title: '商品图片',
        dataIndex: 'commodityCoverUrl',
        key: 'commodityCoverUrl',
        width: 100,
        render: text => <img className={Style['goods-image']} src={text} />
      },
      {
        title: '商品名称',
        dataIndex: 'name',
        key: 'name',
        width: 100
      },
      {
        title: '创造者',
        dataIndex: 'authorName',
        key: 'authorName',
        width: 100
      },
      {
        title: '价格',
        dataIndex: 'commodityPrice',
        key: 'commodityPrice',
        width: 100,
        render: text => text && `¥${text}`
      },
      {
        title: '操作',
        dataIndex: 'a',
        key: 'a',
        render: (text, row, index) => {
          return <>
            {
              this.props.type === 'view' ? '-' : <div>
                {/* <a>查看</a> */}
                <a onClick={() => this.handleDel(index)}>移除</a>
              </div>
            }
          </>
        },
        width: 100
      }
    ]
  }

  imageClick (e) {
    const { width, height } = this.state
    const imgBlock = document.getElementById('img-block')

    const windowScrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
    let imgWidth = width
    let imgHeight = height
    let imgBlockOffsetLeft
    let imgBlockOffsetTop
    let xPoi = e.clientX
    let yPoi = e.clientY
    imgBlockOffsetLeft = imgBlock.offsetLeft
    imgBlockOffsetTop = imgBlock.offsetTop
    let xTotalPoi = imgWidth
    let yTotalPoi = imgHeight + windowScrollHeight

    if (windowScrollHeight > 0) {
      if (windowScrollHeight < imgBlockOffsetTop) {
        yPoi = yPoi - (imgBlockOffsetTop - windowScrollHeight)
        yTotalPoi = imgHeight
      } else if (windowScrollHeight > imgBlockOffsetTop) {
        yPoi = yPoi + (windowScrollHeight - imgBlockOffsetTop)
        yTotalPoi = imgHeight
      }
    } else {
      yPoi = yPoi - imgBlockOffsetTop
    }

    const posX = (xPoi - imgBlockOffsetLeft) / xTotalPoi * 100
    const posY = yPoi / yTotalPoi * 100

    this.setState({
      posX: posX.toFixed(2),
      posY: posY.toFixed(2),
      showModal: true
    })
  }

  getHeightWidth (width, height) {
    const maxWidth = 800
    const maxHight = 600
    let newWidth = width
    let newHeight = height
    if (width <= maxWidth && height <= maxHight) {
      newWidth = width
      newHeight = height
    } else if (width > maxWidth && height <= maxHight) {
      newWidth = maxWidth
      newHeight = (maxWidth / width) * height
    } else if (width <= maxWidth && height < maxHight) {
      newHeight = maxHight
      newWidth = (maxHight / height) * width
    } else if (width > maxWidth && height > maxHight) {
      let scRatio = maxWidth / width
      let scHeight = height * scRatio
      if (scHeight <= maxHight) {
        newWidth = maxWidth
        newHeight = scHeight
      } else {
        scRatio = maxHight / height
        let scWidth = width * scRatio
        newWidth = scWidth
        newHeight = maxHight
      }
    }
    // console.log('width:' + width)
    // console.log('heigh:' + height)
    // console.log('newwidth:' + newWidth)
    // console.log('newheigh:' + newHeight)
    // console.log('>>>>>>>>', {
    //   newWidth, newHeight
    // })
    return {
      newWidth, newHeight
    }
  }

  handleDel (index) {
    const { details } = this.props
    const addTagNodes = this.state.addTagNodes || (details && details.tagNodeList) || []
    const cp = addTagNodes.slice(0)
    cp.splice(index, 1)
    details && this.props.editDetails(cp)
    this.setState({
      addTagNodes: cp
    })
  }

  handleCancel () {
    this.setState({
      showModal: false
    })
    this.props.restGoods()
    setTimeout(() => {
      this.setState({
        goods: null
      })
    }, 1000)
  }

  tagChange (e) {
    this.setState({
      tagName: e.target.value
    })
  }

  directionChange (e) {
    this.setState({
      direction: e
    })
  }

  handleOk () {
    const { posX, posY, tagName, addTagNodes = [], goods, width, height, direction } = this.state
    if (!tagName) {
      message.warning('请输入标签名')
      return
    }
    // if (!goods) {
    //   message.warning('请关联商品')
    //   return
    // }
    const tagNode = {
      posX,
      posY,
      tagName,
      name: goods && goods.name,
      commodityCoverUrl: goods && goods.imgUrl,
      commodityPrice: goods && goods.price,
      authorName: goods && goods.authorName,
      commodityId: goods && goods.commodityId,
      direction
    }

    addTagNodes.push(tagNode)
    this.setState({
      addTagNodes,
      showModal: false,
      goods: null
    })
    this.props.handleOk({
      addTagNodes,
      width,
      height
    })
  }

  goodsIdChange (value) {
    // if (!value) {
    //   message.warning('请输入商品名称')
    //   return
    // }
    this.props.getGoods({
      searchField: value,
      pageSize: 9999,
      pageNo: 1
    })
  }

  // 关联
  handleRelated (item) {
    this.setState({
      goods: item
    })
  }

  componentDidMount () {
    setTimeout(() => {
      const { newWidth: width, newHeight: height } = this.getHeightWidth(document.getElementById('image').width, document.getElementById('image').height)
      this.setState({
        width,
        height
      })
    }, 20)
  }

  componentWillReceiveProps () {
    setTimeout(() => {
      const { newWidth: width, newHeight: height } = this.getHeightWidth(document.getElementById('image').width, document.getElementById('image').height)
      this.setState({
        width,
        height
      })
    }, 300)
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { goodsList, type, details } = this.props
    const { showModal, goods, addTagNodes, width, height } = this.state
    const { image = '' } = this.props

    const mapList = addTagNodes || (details && details.tagNodeList) || []

    return (
      <div className={Style['scenes-com-relatedcom']}>
        <div className={Style['image-container']}>
          <div
            id='img-block'
            className={Style['img-block']}
            // style={{ width: `${width}px`, height: `${height}px`, backgroundImage: `url(${image})` }}
            onClick={type !== 'view' ? this.imageClick : null}
          >
            <img style={{ width: `${width}px`, height: `${height}px` }} src={image} />
            {
              mapList && mapList.map((item, index) => {
                return item.direction === 1 ? <div key={index} className={Style['tag-name']} style={{ top: `${item.posY}%`, left: `${item.posX}%`, transform: 'translate(-93%,-10px)' }}>
                  <div className={Style['name']}>{item.tagName}</div>
                  <div className={Style['line']} />
                  <div className={Style['circle']}>
                    <div className={Style['small-circle']} />
                  </div>
                </div> : <div key={index} className={Style['tag-name']} style={{ top: `${item.posY}%`, left: `${item.posX}%` }}>
                  <div className={Style['circle']}>
                    <div className={Style['small-circle']} />
                  </div>
                  <div className={Style['line']} />
                  <div className={Style['name']}>{item.tagName}</div>
                </div>
                // return <div key={index} className={Style['tag-name']} style={{ top: `${item.posY}%`, left: `${item.posX}%`, transform: 'translate(-100%,0px)' }}>
                //   {
                //     item.direction === '1' ? <>
                //       <div className={Style['name']}>{item.tagName}</div>
                //       <div className={Style['line']} />
                //       <div className={Style['circle']}>
                //         <div className={Style['small-circle']} />
                //       </div>
                //       </> : <>
                //         <div className={Style['circle']}>
                //           <div className={Style['small-circle']} />
                //         </div>
                //         <div className={Style['line']} />
                //         <div className={Style['name']}>{item.tagName}</div></>
                //   }
                // </div>
              })
            }
          </div>
          <img id='image' className={Style['image']} src={image} />
        </div>
        <CustomTable loading={false} columns={this.getTableCols()} dataSource={(mapList) || []} pagination={false} />
        <Modal
          title='添加热区'
          visible={showModal}
          width={600}
          onOk={this.handleOk}
          destroyOnClose
          onCancel={this.handleCancel}
        >
          <Form {...formItemLayout}>
            <Form.Item label='标签名'>
              {getFieldDecorator('tagName')(
                <Input placeholder='请输入标签名' onChange={(e) => debounce(this.tagChange(e), 300)} />
              )}
            </Form.Item>
            <Form.Item label='方向'>
              {getFieldDecorator('direction')(
                <Select onChange={this.directionChange} placeholder='选择方向'>
                  <Option value={1}>左</Option>
                  <Option value={2}>右</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label='商品'>
              {
                goods ? <div className={Style['goods-detail']}>
                  <div className={Style['title']}>{goods.name}</div>
                  <div className={Style['goods-image']} style={{ backgroundImage: `url(${goods.imgUrl})` }} />
                </div> : <>
                  <Search
                    style={{ width: '380px' }}
                    placeholder='请输入商品名称'
                    onSearch={value => this.goodsIdChange(value)}
                  />
                  {
                    goodsList && <div className={Style['goods-container']}>
                      {
                        goodsList.map((item, index) => {
                          return <div key={index} className={Style['goods']}>
                            <div className={Style['left']}>
                              <div className={Style['image']} style={{ backgroundImage: `url(${item.imgUrl})` }} />
                              <div className={Style['name-price']} >
                                <div className={Style['name']}>{item.name}</div>
                                <div className={Style['price']}>{item.price}</div>
                              </div>
                            </div>
                            <div className={Style['button']} onClick={() => this.handleRelated(item)}>关联</div>
                          </div>
                        })
                      }
                    </div>
                  }
                </>
              }
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}

RelatedCom.propTypes = {
  stepChange: PropTypes.func,
  details: PropTypes.any,
  image: PropTypes.string
}

const Related = Form.create()(RelatedCom)

export default Related
